package insert;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

/**
 * Servlet implementation class ModifierProfileServlet
 */
public class ModifierProfileServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ModifierProfileServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		RequestDispatcher dis;
		Connection con = null;
		
		Integer membre = (Integer)session.getAttribute("user_id");
		if(membre == null){
			dis = request.getRequestDispatcher("/login.jsp");
			dis.forward(request, response);
			return;
		}
		
		try{
			Context namingContext;
			PreparedStatement pstmt;
			ResultSet rs;
			
			namingContext = new InitialContext();
			DataSource dataSource = (DataSource)namingContext.lookup("java:comp/env/jdbc/MiniIBay");
			con = dataSource.getConnection();
			
			pstmt = con.prepareStatement("SELECT m.numero_rue, m.rue, m.code_postal, m.ville, m.telephone, m.mail FROM `membre` m WHERE m.id_membre=?");
			pstmt.setInt(1, membre);
			
			rs = pstmt.executeQuery();
			while(rs.next()){
				request.setAttribute("numrue", rs.getInt("numero_rue"));
				request.setAttribute("rue", rs.getString("rue"));
				request.setAttribute("codepostal", rs.getInt("code_postal"));
				request.setAttribute("ville", rs.getString("ville"));
				request.setAttribute("telephone", rs.getString("telephone"));
				request.setAttribute("mail", rs.getString("mail"));
			}
			
			dis = request.getRequestDispatcher("modifierprofile.jsp");
			dis.forward(request, response);
		}catch(NamingException e){
			// TODO Auto-generated catch block
			e.printStackTrace();
			response.sendRedirect("profile");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			response.sendRedirect("profile");
		} finally {
			try {
				if(con != null) con.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		RequestDispatcher dis;
		Connection con = null;
		
		Integer membre = (Integer)session.getAttribute("user_id");
		if(membre == null){
			dis = request.getRequestDispatcher("/login.jsp");
			dis.forward(request, response);
			return;
		}
		
		String numRue = request.getParameter("numrue");
		int iNumRue = 0;
		String rue = request.getParameter("rue");
		String codePostal = request.getParameter("codepostal");
		int iCodePostal = 0;
		String ville = request.getParameter("ville");
		String telephone = request.getParameter("telephone");
		String mail = request.getParameter("mail");
		
		List<String> erreur = new LinkedList<String>();
		
		if(numRue.isEmpty() || rue.isEmpty() || codePostal.isEmpty() || ville.isEmpty() || telephone.isEmpty() || mail.isEmpty()) {
			erreur.add("Un des champs obligatoire n'est pas renseign�");
		}
		
		if(numRue.length() > 4)		erreur.add("La taille du numero de rue est trop longue (maximum 4 chiffres)");
		else{
			try{
				iNumRue = Integer.parseInt(numRue);
			}catch(NumberFormatException e){
				erreur.add("Le numero de la rue doit �tre un nombre");
			}
		}
		
		if(rue.length() > 100) 		erreur.add("La taille de la rue est trop longue (maximum 100 caract�res)");
		if(codePostal.length()!=5)	erreur.add("Le code postal doit contenir 5 chiffres");
		else{
			try{
				iCodePostal = Integer.parseInt(codePostal);
			}catch(NumberFormatException e){
				erreur.add("Le code postal doit �tre un nombre");
			}
		}
		if(ville.length() > 50) 	erreur.add("La taille de la ville est trop longue (maximum 50 caract�res)");
		if(telephone.length() > 15) erreur.add("La taille du num�ro de t�l�phone est trop longue (maximum 15 chiffres)");
		else{
			try{
				Integer.parseInt(telephone);
			}catch(NumberFormatException e){
				erreur.add("Le num�ro de t�l�phone doit �tre un nombre");
			}
		}
		if(mail.length() > 80) 		erreur.add("La taille du mail est trop longue (maximum 80 caract�res)");
		
		if(!erreur.isEmpty()){ //Donn�es du formulaire incorrectes
			request.setAttribute("numrue", request.getParameter("numrue"));
			request.setAttribute("rue", request.getParameter("rue"));
			request.setAttribute("codepostal", request.getParameter("codepostal"));
			request.setAttribute("ville", request.getParameter("ville"));
			request.setAttribute("telephone", request.getParameter("telephone"));
			request.setAttribute("mail", request.getParameter("mail"));
			
			request.setAttribute("erreur", erreur);
			dis=request.getRequestDispatcher("modifierprofile.jsp");
			dis.forward(request,response);
		}else{ //Donn�es correctes, envoie de la requete SQL
			PreparedStatement pstmt;
			try {
				Context namingContext = new InitialContext();
				DataSource dataSource = (DataSource)namingContext.lookup("java:comp/env/jdbc/MiniIBay");
				con = dataSource.getConnection();
				
				pstmt = con.prepareStatement("UPDATE `membre` SET `numero_rue`=?, `rue`=?, `code_postal`=?, `ville`=?, `telephone`=?, `mail`=? WHERE `id_membre`=?");
				pstmt.setInt(1, iNumRue);
				pstmt.setString(2, rue);
				pstmt.setInt(3, iCodePostal);
				pstmt.setString(4, ville);
				pstmt.setString(5, telephone);
				pstmt.setString(6, mail);
				pstmt.setInt(7, membre);
				pstmt.executeUpdate();
				
				response.sendRedirect("/MiniIBay/profile");
			} catch (NamingException e) {
				response.sendRedirect("../home");
			} catch (SQLException e) {
				response.sendRedirect("../home");
			}finally{
				if(con != null){
					try {
						con.close();
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
	}

}
